﻿package com.ghostmonk.media
{
	
	import caurina.transitions.Tweener;
	
	import flash.display.*;
	import flash.events.*;
	import flash.geom.*;
	import flash.media.*;
	import flash.net.*;
	import flash.text.*;
	
	public class StillImageLoader extends Sprite
	{ 
		private var _img:Loader = new Loader();
		private var _imgURL:String;
		private var _buffer:MovieClip = new Buffer();
		private var _percentageTracker:TextField;
		private var _width:Number;
		private var _height:Number;
		
		public function get thisWidth():Number
		{
			return _width;
		}
		
		public function get thisHeight():Number
		{
			return _height;
		}
	
		public function StillImageLoader(xPosition:Number = 0)
		{
			addChild(_img);
			_percentageTracker = _buffer.percentDisplay;
			_buffer.addChild(_percentageTracker);
			_img.alpha = 0;
			_buffer.x = xPosition;
		}
		
		public function set bufferX(xValue:Number):void
		{
			_buffer.x = xValue;
		}
		
		public function loadNewImg(imageURL:String, yPosition:Number, toStage:Boolean = false):void
		{
			Tweener.addTween(_img, {alpha:0, time:0.5, onComplete:initLoad, onCompleteParams:[imageURL]});
			_buffer.y = yPosition - 150;
			toStage ? stage.addChild(_buffer) : addChild(_buffer);
			_buffer.alpha = 0;
			Tweener.addTween(_buffer, {alpha:1, y:yPosition, time:0.5});
		}
		
		public function clearImg():void
		{
			_img.unload();
			Tweener.addTween(_buffer, {alpha:0, y:_buffer.y + 150, time:0.5});
		}
		
		private function initLoad(imageURL:String):void
		{
			_img.unload();
			_img.load(new URLRequest(imageURL));
			_percentageTracker.text = "0%";
			_img.contentLoaderInfo.addEventListener(Event.OPEN, onOpen);
			_img.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, imgProgress); 
			_img.contentLoaderInfo.addEventListener(Event.COMPLETE, imgComplete);
			_img.contentLoaderInfo.addEventListener(Event.INIT, onInit);
		}
		
		private function onInit(e:Event):void
		{
			_width = _img.contentLoaderInfo.width;
			_height = _img.contentLoaderInfo.height;
			dispatchEvent(e);
		}
		
		private function onOpen(e:Event):void
		{
			dispatchEvent(e);
		}
		
		private function imgProgress(e:ProgressEvent):void
		{
			var percent:int = e.target.bytesLoaded > 0 ? e.target.bytesLoaded/e.target.bytesTotal * 100 : 0;
			_percentageTracker.text = percent + "%";
		}
		
		private function imgComplete(e:Event):void
		{
			dispatchEvent(e);
			_percentageTracker.text = "";
			Tweener.addTween(_buffer, {alpha:0, y:_buffer.y + 50, time:0.5});
			Tweener.addTween(_img, {alpha:1, time:1});
			_img.contentLoaderInfo.removeEventListener(Event.INIT, onOpen);
			_img.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS, imgProgress); 
			_img.contentLoaderInfo.removeEventListener(Event.COMPLETE, imgComplete);
			_img.contentLoaderInfo.removeEventListener(Event.INIT, onInit);
		}
		
	}
}